import { loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import legacy from '@vitejs/plugin-legacy';
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'

import postcssPxtorem from 'postcss-pxtorem';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

// 获取当前模式（development 或 production）
const mode = process.env.NODE_ENV;
// 加载环境变量
const env = loadEnv(mode, process.cwd());

export default {
  server: {
    port: 8000, //指定端口号
    host: '0.0.0.0', //可局域网IP访问
    open: true,
    proxy: proxy(),
  },
  plugins: [
    vue(),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    ElementPlus({
      useSource: true, // 使用 ES Module 版本的 Element Plus
    }),
    legacy({
      targets: ['Chrome 69'],
      modernPolyfills: true,
    }),
    createSvgIconsPlugin({
      // 指定要处理的 SVG 文件夹路径
      iconDirs: [resolve(process.cwd(), 'src/assets/icon')],
      // 指定要生成的组件类型
      symbolId: 'icon-[dir]-[name]',
    })
  ],
  resolve: {
    alias: {
      '@': '/src',
    },
  },
  css: {
    postcss: {
      plugins: (Number(env.VITE_DESIGN_HEIGHT)>0 || Number(env.VITE_DESIGN_WIDTH)>0) ? [
        postcssPxtorem({
          rootValue: 20,
          exclude: /node_modules/,
          propList: ['*'],// 需要转换的属性，这里选择全部转换
          selectorBlackList: [".el-"],//过滤掉el-开头的class
        }),
      ] : [],
    },
  },
  base: '',//路径
  build: {
    emptyOutDir: true,
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        // nested: resolve(__dirname, 'nested/index.html')
      }
    }
  }
}

function proxy() {
  if(!env.VITE_PROXY){
    return {};
  }
  let obj = {};
  let arr = JSON.parse(env.VITE_PROXY);
  arr.forEach(item => {
    obj[item[0]] = {
      target: item[1]=='PROXY_URL'?env.VITE_PROXY_URL:item[1], //跨域目标
      changeOrigin: true,
      // rewrite: (path) => path.replace(new RegExp(`^${item[0]}`), '')
    }
  });
  return obj;
}